package cn.xf.districonfig.client.util;

import cn.xf.districonfig.client.util.json.BasicJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class RpcUtils {

    private static Logger logger = LoggerFactory.getLogger(RpcUtils.class);

    private RpcUtils() {

    }

    /**
     * get and valid
     *
     * @param url
     * @param requestBody
     * @param timeout
     * @return
     */
    public static Map<String, Object> getAndValid(String url, String requestBody, int timeout){

        // resp json
        String respJson = BasicHttpUtil.postBody(url, requestBody, timeout);
        if (respJson == null) {
            return null;
        }

        // parse obj
        Map<String, Object> respObj = BasicJson.parseMap(respJson);
        int code = Integer.valueOf(String.valueOf(respObj.get("code")));
        if (code != 200) {
            logger.info("request fail, msg={}", (respObj.containsKey("msg")?respObj.get("msg"):respJson) );
            return null;
        }
        return respObj;
    }

    /**
     * find
     *
     * @return
     */
    public static Map<String, Object> find(String adminAddressUrl, String paramsJson) {
        // url + param
        String url = adminAddressUrl + "/conf/find";

        return getAndValid(url, paramsJson, 5);
    }
}
